{% extends 'base.html' %}

{% block content %}
<div class="row mb-4">
    <div class="col-md-12">
        <h1>AI 知识库搜索</h1>
        <p>使用AI搜索相关问题和解决方案</p>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h5>搜索问题</h5>
    </div>
    <div class="card-body">
        <form id="ai-search-form">
            <div class="form-group">
                <label for="search-query">输入搜索内容</label>
                <textarea class="form-control" id="search-query" rows="3" placeholder="请描述您遇到的问题或需要查找的内容..."></textarea>
            </div>
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-search"></i> AI 搜索
            </button>
        </form>
    </div>
</div>

<div class="card mt-4" id="search-results" style="display: none;">
    <div class="card-header">
        <h5>搜索结果</h5>
    </div>
    <div class="card-body">
        <div id="loading-indicator" class="text-center py-4" style="display: none;">
            <div class="spinner-border" role="status">
                <span class="sr-only">搜索中...</span>
            </div>
            <p class="mt-2">AI正在分析您的问题并搜索相关内容...</p>
        </div>
        
        <div id="results-container"></div>
    </div>
</div>

<script>
// 使用纯JavaScript实现，移除jQuery依赖

document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const searchForm = document.getElementById('ai-search-form');
    const searchQuery = document.getElementById('search-query');
    const searchResults = document.getElementById('search-results');
    const loadingIndicator = document.getElementById('loading-indicator');
    const resultsContainer = document.getElementById('results-container');
    
    // 表单提交事件
    searchForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const query = searchQuery.value.trim();
        if (!query) {
            alert('请输入搜索内容');
            return;
        }
        
        // 显示搜索结果区域和加载指示器
        searchResults.style.display = 'block';
        loadingIndicator.style.display = 'block';
        resultsContainer.innerHTML = '';
        
        // 发送搜索请求
        const xhr = new XMLHttpRequest();
        xhr.open('POST', '{{ url_for('main.ai_search') }}', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
            if (xhr.status >= 200 && xhr.status < 400) {
                // 隐藏加载指示器
                loadingIndicator.style.display = 'none';
                
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.results && response.results.length > 0) {
                        // 显示搜索结果
                        let resultsHtml = '<div class="list-group">';
                        response.results.forEach(function(result) {
                            // 根据相关性分数确定背景颜色深度
                            let scoreClass = '';
                            if (result.score > 3) scoreClass = 'list-group-item-success';
                            else if (result.score > 1.5) scoreClass = 'list-group-item-info';
                            else if (result.score > 0.5) scoreClass = 'list-group-item-warning';
                            
                            // 确保issue_id是有效的整数
                            const issueId = parseInt(result.id);
                            if (isNaN(issueId)) {
                                console.error('无效的issue_id:', result.id);
                                return;
                            }
                            const issueUrl = "{{ url_for('main.view_issue', issue_id=0) }}".replace('0', issueId);
                            
                            // 构建优先级徽章样式
                            let priorityClass = 'secondary';
                            let priorityText = '低';
                            if (result.priority === 'urgent') {
                                priorityClass = 'danger';
                                priorityText = '紧急';
                            } else if (result.priority === 'high') {
                                priorityClass = 'warning';
                                priorityText = '高';
                            } else if (result.priority === 'medium') {
                                priorityClass = 'info';
                                priorityText = '中';
                            }
                            
                            resultsHtml += `
                                <a href="${issueUrl}" class="list-group-item list-group-item-action ${scoreClass}">
                                    <div class="d-flex justify-content-between">
                                        <h6 class="mb-1">${result.title}</h6>
                                        <span class="badge badge-primary">相关性: ${result.score}</span>
                                    </div>
                                    <p class="mb-1 text-sm text-muted">${result.description}</p>
                                    <div class="d-flex justify-content-between text-xs">
                                        <span class="badge badge-secondary">状态: ${result.status === 'open' ? '未解决' : '已解决'}</span>
                                        <span class="badge badge-${priorityClass}">优先级: ${priorityText}</span>
                                    </div>
                                </a>
                            `;
                        });
                        resultsHtml += '</div>';
                        resultsContainer.innerHTML = resultsHtml;
                    } else {
                        // 没有找到结果
                        resultsContainer.innerHTML = '<div class="alert alert-info text-center">没有找到相关问题，请尝试使用其他关键词。</div>';
                    }
                } catch (e) {
                    resultsContainer.innerHTML = '<div class="alert alert-danger text-center">处理搜索结果时出错。</div>';
                    console.error('解析响应错误:', e);
                }
            } else {
                // 请求错误
                loadingIndicator.style.display = 'none';
                resultsContainer.innerHTML = '<div class="alert alert-danger text-center">搜索出错，请稍后重试。</div>';
                console.error('搜索请求错误:', xhr.status);
            }
        };
        xhr.onerror = function() {
            loadingIndicator.style.display = 'none';
            resultsContainer.innerHTML = '<div class="alert alert-danger text-center">网络错误，请检查您的连接。</div>';
            console.error('搜索网络错误');
        };
        xhr.send('query=' + encodeURIComponent(query));
    });
    
    // 添加自动补全功能（简单实现）
    const commonQueries = [
        '系统崩溃问题',
        '页面加载缓慢',
        '数据库连接超时',
        '用户认证失败',
        '文件上传错误'
    ];
    
    searchQuery.addEventListener('input', function() {
        const input = this.value.toLowerCase();
        if (input.length > 2) {
            // 在实际项目中可以实现更复杂的自动补全逻辑
        }
    });
});
</script>
{% endblock %}